<template>
  <view class="skills-container">
    <!-- 导航栏 -->
    <nav-bar></nav-bar>
    <!-- 顶部操作栏 -->
    <view class="header-bar">
      <text class="title">选择技能</text>
      <text class="select-all" @tap="handleSelectAll">
        {{ isAllSelected ? '取消全选' : '全选' }}
      </text>
    </view>

    <!-- 技能列表 -->
    <view class="skills-list">
      <view 
        class="skill-item" 
        v-for="(skill, index) in skillsList" 
        :key="index"
        @tap="selectSkill(skill.value)"
      >
        <view class="radio-wrapper">
          <view 
            class="custom-radio" 
            :class="{ 'checked': selectedSkills.includes(skill.value) }"
          >
            <view class="inner-circle"></view>
          </view>
        </view>
        <view class="skill-info">
          <text class="skill-name">{{ skill.name }}</text>
          <text class="skill-desc">{{ skill.description }}</text>
        </view>
      </view>
    </view>
    
    <!-- 保存按钮 -->
    <view class="bottom-bar">
      <button 
        class="save-btn" 
        :disabled="selectedSkills.length === 0"
        @tap="handleSave"
      >保存</button>
    </view>
  </view>
</template>

<script>
import TechNavBar from '@/components/tech-nav-bar.vue'
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
  components: {
    TechNavBar,
    NavBar
  },
  
  data() {
    return {
      selectedSkills: [], // 选中的技能数组
      skillsList: [],
      isMultiSelect: true, // 默认多选模式
      techId: '', // 添加techId
      techInfo: null // 添加techInfo存储技师信息
    }
  },
  
  computed: {
    isAllSelected() {
      return this.skillsList.length > 0 && this.selectedSkills.length === this.skillsList.length
    }
  },
  
  onLoad() {
    // 从本地存储获取techId
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo) {
      this.techId = userInfo.techId
    }
    
    this.loadSkillsList()
    this.loadCurrentSkill()
  },
  
  methods: {
    // 处理全选/取消全选
    handleSelectAll() {
      if (this.isAllSelected) {
        // 取消全选
        this.selectedSkills = []
      } else {
        // 全选
        this.selectedSkills = this.skillsList.map(skill => skill.value)
      }
    },

    // 加载技能列表
    async loadSkillsList() {
      uni.showLoading({
        title: '加载中...'
      })
      
      try {
        const result = await uni.request({
          url: `${uni.$config.baseUrl}/category/category/listAll`,
          method: 'GET'
        })
        
        if (result.data.code === 200) {
          // 转换后端数据格式为前端所需格式，确保value是字符串类型
          this.skillsList = result.data.rows.map(item => ({
            name: item.categoryName,
            value: item.id.toString(), // 转换为字符串
            description: item.remark || '暂无描述'
          }))
          
          // 在技能列表加载完成后再加载当前技能
          await this.loadCurrentSkill()
        } else {
          throw new Error(result.data.msg || '获取技能列表失败')
        }
      } catch (err) {
        console.error('获取技能列表失败:', err)
        uni.showToast({
          title: err.message || '获取技能列表失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 加载当前技能
    async loadCurrentSkill() {
      if (!this.techId) {
        console.error('未找到techId')
        return
      }

      uni.showLoading({
        title: '加载中...'
      })
      
      try {
        const result = await uni.request({
          url: `${uni.$config.baseUrl}/technician/technician/${this.techId}`,
          method: 'GET'
        })
        
        if (result.data.code === 200) {
          this.techInfo = result.data.data // 保存技师信息
          if (this.techInfo.categoryIds) {
            // 将categoryIds字符串转为数组并确保是字符串类型
            const categoryIds = this.techInfo.categoryIds.split(',').map(id => id.toString())
            // 过滤出在skillsList中存在的技能ID
            this.selectedSkills = categoryIds.filter(id => 
              this.skillsList.some(skill => skill.value === id)
            )
          }
        }
      } catch (err) {
        console.error('获取技能信息失败:', err)
        uni.showToast({
          title: '获取信息失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 选择技能
    selectSkill(value) {
      const strValue = value.toString()
      if (this.isMultiSelect) {
        // 多选模式
        const index = this.selectedSkills.indexOf(strValue)
        if (index === -1) {
          this.selectedSkills.push(strValue)
        } else {
          this.selectedSkills.splice(index, 1)
        }
      } else {
        // 单选模式
        this.selectedSkills = [strValue]
      }
    },
    
    // 保存技能设置
    async handleSave() {
      if (this.selectedSkills.length === 0) return
      
      uni.showLoading({
        title: '保存中...'
      })
      
      try {
        // 使用techInfo并更新categoryIds
        const updateData = {
          ...this.techInfo,
          categoryIds: this.selectedSkills.join(',')
        }
        
        const result = await uni.request({
          url: `${uni.$config.baseUrl}/technician/technician`,
          method: 'PUT',
          data: updateData,
          header: {
            'Authorization': uni.getStorageSync('token')
          }
        })
        
        if (result.data.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(result.data.msg || '保存失败')
        }
      } catch (err) {
        console.error('保存技能失败:', err)
        uni.showToast({
          title: err.message || '保存失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.skills-container {
  min-height: 100vh;
  background: #F5F5F5;
  padding-bottom: 120rpx;
  
  .header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    background: #FFFFFF;
    
    .title {
      font-size: 32rpx;
      color: #333333;
      font-weight: 500;
    }
    
    .select-all {
      font-size: 28rpx;
      color: #2B85E4;
      padding: 10rpx 20rpx;
    }
  }
  
  .skills-list {
    background: #FFFFFF;
    margin-top: 20rpx;
    
    .skill-item {
      display: flex;
      align-items: center;
      padding: 30rpx;
      border-bottom: 2rpx solid #F5F5F5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .radio-wrapper {
        margin-right: 20rpx;
        
        .custom-radio {
          width: 40rpx;
          height: 40rpx;
          border: 2rpx solid #CCCCCC;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          
          &.checked {
            border-color: #2B85E4;
            
            .inner-circle {
              width: 24rpx;
              height: 24rpx;
              background: #2B85E4;
              border-radius: 50%;
            }
          }
        }
      }
      
      .skill-info {
        flex: 1;
        
        .skill-name {
          font-size: 32rpx;
          color: #333333;
          margin-bottom: 8rpx;
          display: block;
        }
        
        .skill-desc {
          font-size: 24rpx;
          color: #999999;
          display: block;
        }
      }
    }
  }
  
  .bottom-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx 30rpx;
    background: #FFFFFF;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .save-btn {
      height: 80rpx;
      line-height: 80rpx;
      background: #2B85E4;
      color: #FFFFFF;
      font-size: 32rpx;
      border-radius: 40rpx;
      
      &[disabled] {
        opacity: 0.6;
      }
      
      &::after {
        border: none;
      }
    }
  }
}
</style> 